package com.clickpaas.timelineofUN.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JsonUtil {

    public static JSONObject jsonStrToJson(String data) {

        if (data != null) {
            try {
                return JSON.parseObject(data);
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    public static JSONObject objToJson(Object data) {

        if (data != null) {
            try {
                String s = JSON.toJSONString(data);
                return JSON.parseObject(s);
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    /**
     * 通过JSONObject.parseObject把String转换为对象
     * @param jsonStr
     * @param model
     * @return
     */
    public static <T> T getStringToObject(String jsonStr, Class<T> model) {
        if (jsonStr != null) {
            try {
                return JSONObject.parseObject(jsonStr, model);
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    /**
     * 通过JSONArray.parseArray把json转换为List<T>
     *
     * @param jsonStr
     * @param model
     * @return
     */
    public static <T> List<T> getStringToList(String jsonStr, Class<T> model) {
        if (jsonStr != null) {
            try {
                return (List<T>) JSONArray.parseArray(jsonStr, model);
            } catch (Exception ignored) {
            }
        }
        return null;
    }

}
